package vn.edu.hut.soict.translate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import vn.hus.nlp.tagger.IConstants;
import vn.hus.nlp.tagger.TaggerOptions;
import edu.stanford.nlp.ling.WordTag;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;

public class POSTagger {
	private static final String DEFAULT_MODELS = "models/vtb.tagger";

	private MaxentTagger tagger;

	public POSTagger(String resourceDir) throws IOException,
			ClassNotFoundException {
		tagger = new MaxentTagger(resourceDir + "/" + DEFAULT_MODELS);
	}

	public List<WordTag> tagList(List<String> words) throws Exception {
		List<WordTag> tokens = new ArrayList<WordTag>();
		// replace the space characters of the word in the word list by
		// underscores chars and build a string containing all the words
		StringBuffer buffer = new StringBuffer(words.size() * 5);
		for (String word : words) {
			buffer.append(word.replace(' ', '_'));
			buffer.append(" ");
		}
		// tag the tokenized string
		// changed from version 2.0 of Stanford Maxent Tagger
		String taggedString = tagger.tagTokenizedString(buffer.toString());
		// split the tagged string using the word/tag delimiter
		String[] pairs = taggedString.split("\\s+");
		String word, tag;
		for (String pair : pairs) {
			String[] wt = pair.split(IConstants.DELIM);
			if (wt.length == 2) {
				word = wt[0];
				// recover the space character if user don't want underscores
				if (!TaggerOptions.UNDERSCORE) {
					word = wt[0].replaceAll("_", " ");
				}
				tag = wt[1];
			}
			else if (wt.length > 2) {
				// the case of date with / separator, for example 20/10/1980/N
				// the word is 20/10/1980
				word = wt[0];
				for (int j = 1; j < wt.length - 1; j++) {
					word += IConstants.DELIM + wt[j];
				}
				// the tag is the last part
				tag = wt[wt.length - 1];
			}
			else { // wt.length < 2
				word = "";
				tag = "";
				System.err.println("There is an error.");
			}
			tokens.add(new WordTag(word, tag));
		}
		return tokens;
	}
}
